<template>
    <el-tabs v-model="carModelId" class="demo-tabs" @tab-change="handleTabChange">
        <el-tab-pane v-for="(item, index) in examType === 1 ? props.examPeopleList : props.examNumList" :key="index"
            :label="item.typeName" :name="index"></el-tab-pane>
    </el-tabs>
    <el-row :gutter="20">
        <el-col :sm="24" :md="12" :lg="6">
            <div class="card" :class="{ 'card-selected': examType === 1 }" @click="examClick(1)">
                <div class="card-header">
                    <h2>今日考试人数（人）</h2>
                </div>
                <div class="data-container">
                    <div class="main-value">
                        {{
                            props.examPeopleList[carModelId].aoList[props.examPeopleList[carModelId].aoList.length - 1].data
                        }}
                    </div>
                </div>
                <div class="comparison-container">
                    <div class="comparison-item">
                        <div class="comparison-title">昨日：</div>
                        <div class="comparison-value neutral">{{ props.examPeopleList[carModelId].yesterdayData }}</div>
                    </div>
                    <div class="comparison-item">
                        <div class="comparison-title">近7日：</div>
                        <div class="comparison-value neutral">{{ props.examPeopleList[carModelId].last7DaysTotal }}
                        </div>
                    </div>
                    <div class="comparison-item">
                        <div class="comparison-title">近30日：</div>
                        <div class="comparison-value neutral">{{ props.examPeopleList[carModelId].last30DaysTotal }}
                        </div>
                    </div>
                </div>
            </div>
            <div class="card marT30" :class="{ 'card-selected': examType === 2 }" @click="examClick(2)">
                <div class="card-header">
                    <h2>今日考试次数（次）</h2>
                </div>
                <div class="data-container">
                    <div class="main-value">
                        {{
                            props.examNumList[carModelId].aoList[props.examNumList[carModelId].aoList.length - 1].data
                        }}
                    </div>
                </div>
                <div class="comparison-container">
                    <div class="comparison-item">
                        <div class="comparison-title">昨日：</div>
                        <div class="comparison-value neutral">{{ props.examNumList[carModelId].yesterdayData }}</div>
                    </div>
                    <div class="comparison-item">
                        <div class="comparison-title">近7日：</div>
                        <div class="comparison-value neutral">{{ props.examNumList[carModelId].yesterdayData }}</div>
                    </div>
                    <div class="comparison-item">
                        <div class="comparison-title">近30日：</div>
                        <div class="comparison-value neutral">{{ props.examNumList[carModelId].yesterdayData }}</div>
                    </div>
                </div>
            </div>
        </el-col>
        <el-col :sm="24" :md="12" :lg="18">
            <div class="card-header">
                <h2>{{ examType === 1 ? '考试人数' : '考试次数' }}</h2>
            </div>
            <div class="chart" ref="chartRef"></div>
        </el-col>
    </el-row>
</template>
<script lang="ts" setup>
import * as echarts from 'echarts'
import { hexToRgba, getCssVar } from '@/utils/ui'
import { EChartsOption } from 'echarts'
import { useChart } from '@/composables/useChart'
import { onMounted, watch, nextTick, ref, computed } from 'vue'

const props = defineProps({
    examPeopleList: {
        type: Array<any>,
        default: () => []
    },
    examNumList: {
        type: Array<any>,
        default: () => []
    }
})

const carModelId = ref(0)
const examType = ref(1)

const {
    chartRef,
    isDark,
    initChart,
    updateChart,
    getAxisLabelStyle,
    getAxisLineStyle,
    getAxisTickStyle,
    getSplitLineStyle
} = useChart()

// 计算当前tab下的真实数据
const realData = computed(() => {
    if (examType.value === 1) {
        const list = props.examPeopleList[carModelId.value]
        return list && list.aoList ? list.aoList.map((e: any) => e.data) : []
    } else {
        const list = props.examNumList[carModelId.value]
        return list && list.aoList ? list.aoList.map((e: any) => e.data) : []
    }
})

// 计算当前tab下的x轴
const xAxisData = computed(() => {
    if (examType.value === 1) {
        const list = props.examPeopleList[carModelId.value]
        return list && list.aoList ? list.aoList.map((e: any) => e.statDate.slice(5, 10)) : []
    } else {
        const list = props.examNumList[carModelId.value]
        return list && list.aoList ? list.aoList.map((e: any) => e.statDate.slice(5, 10)) : []
    }
})

// 初始化动画函数，确保 DOM 已经渲染且有宽高
const initChartWithAnimation = () => {
    const tryInit = () => {
        nextTick(() => {
            const el = chartRef.value as HTMLElement
            if (el && el.clientWidth > 0 && el.clientHeight > 0) {
                initChart(options(true))
                updateChart(options(false))
            } else {
                window.addEventListener('load', () => {
                    initChart(options(true))
                    updateChart(options(false))
                }, { once: true })
            }
        })
    }
    tryInit()
}

// 监听tab切换和examType切换，更新图表
watch([carModelId, examType], () => {
    nextTick(() => {
        const el = chartRef.value as HTMLElement
        if (el && el.clientWidth > 0 && el.clientHeight > 0) {
            updateChart(options())
        } else {
            window.addEventListener('load', () => {
                updateChart(options())
            }, { once: true })
        }
    })
})

// 监听暗黑模式
watch(isDark, () => {
    nextTick(() => {
        const el = chartRef.value as HTMLElement
        if (el && el.clientWidth > 0 && el.clientHeight > 0) {
            updateChart(options())
        } else {
            window.addEventListener('load', () => {
                updateChart(options())
            }, { once: true })
        }
    })
})

onMounted(() => {
    initChartWithAnimation()
})

const options: (isInitial?: boolean) => EChartsOption = (isInitial) => {
    const isInit = isInitial || false
    return {
        animation: true,
        animationDuration: 0,
        animationDurationUpdate: 0,
        grid: {
            left: '2.2%',
            right: '3%',
            bottom: '0%',
            top: '10px',
            containLabel: true
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xAxisData.value,
            axisTick: getAxisTickStyle(),
            axisLabel: getAxisLabelStyle(true),
            axisLine: getAxisLineStyle(true)
        },
        yAxis: {
            type: 'value',
            min: 0,
            max: realData.value.length > 0 ? realData.value.reduce((prev: any, curr: any) => Math.max(prev, curr), 0) : 0,
            axisLabel: getAxisLabelStyle(true),
            axisLine: getAxisLineStyle(!isDark.value),
            splitLine: getSplitLineStyle(true)
        },
        series: [
            {
                name: examType.value === 1 ? '考试人数' : '考试次数',
                color: getCssVar('--main-color'),
                type: 'line',
                stack: '总量',
                data: isInit ? new Array(12).fill(0) : realData.value,
                smooth: true,
                symbol: 'none',
                lineStyle: {
                    width: 2.2
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: hexToRgba(getCssVar('--el-color-primary'), 0.15).rgba
                        },
                        {
                            offset: 1,
                            color: hexToRgba(getCssVar('--el-color-primary'), 0.01).rgba
                        }
                    ])
                },
                animationDuration: 0,
                animationDurationUpdate: 1500
            }
        ]
    }
}

const handleTabChange = (e: any) => {
    carModelId.value = e
}

const examClick = (e: number) => {
    if (examType.value !== e) {
        examType.value = e
        carModelId.value = 0 // 切换类型时重置tab为第一个
    }
}
</script>
<style lang="scss" scoped>
.card {
    background: #f7f8fa;
    border-radius: 16px;
    padding: 30px;
    /* 预留边框空间，防止有无边框切换时抖动 */
    box-sizing: border-box;
    border: 2px solid transparent;
    transition: border-color 0.2s;
}

.card-selected {
    border-color: var(--el-color-primary, #409EFF);
}

.card-header {
    display: flex;
    align-items: center;
    margin-bottom: 25px;
    color: #2c3e50;
}

.card-header h2 {
    font-weight: 600;
    font-size: 20px;
}

.data-container {
    margin-bottom: 25px;
}

.main-value {
    font-size: 48px;
    font-weight: 700;
    color: #333;
    margin-bottom: 15px;
}

.comparison-container {
    display: flex;
    padding-top: 20px;
}

.comparison-item {
    display: flex;
    text-align: center;
    padding-right: 15px;
}

.comparison-title {
    font-size: 14px;
    color: #7f8c8d;
    margin-bottom: 8px;
}

.comparison-value {
    font-size: 18px;
    font-weight: 600;
}

.neutral {
    color: #7f8c8d;
}

.marT30 {
    margin-top: 30px;
}

.chart {
    width: 100%;
    height: calc(100% - 30px);
}
</style>